<?php

namespace app\api\model;

use app\common\library\Log;
use think\Model;

Class Leshuapay extends Model {
    // 测试环境地址
//    private $url = "https://t-paygate.lepass.cn/cgi-bin/lepos_pay_gateway.cgi";
    // 正式环境地址
     private $url = "https://paygate.leshuazf.com/cgi-bin/lepos_pay_gateway.cgi";

    private $merchant_id = '';
    private $key = '';

    // 交易成功回调地址，如不接收回调不必提供
    private $callback_url = "";

    public function __construct($merchant_id = '', $key = '') {


    }

    /**
     * 生成指定金额的二维码，服务窗支付
     * 仅支持支付宝，微信已经停用此支付方式
     */
    public function getOrder($param){
        global $_W;
        $amount = $param['price'] *100;
        $jspay_flag = $param['jspay_flag'] ?? '';
        $openid = $param['openid'] ?? '';
        $notify_url = urlencode(request()->domain().'/addons/thirdpay/leshuapay_notify');

//        $notify_url = urlencode($_W['siteroot'].'addons/ewei_shopv2/payment/leshuapay/notify.php'),
        $pay_way = getLeshuapayType($param['paytype']);

        if ($pay_way == 'ZFBZF'){
            $jspay_flag = $jspay_flag==2?$jspay_flag:0;
        }elseif ($pay_way == 'WXZF'){
            $jspay_flag = $jspay_flag==2?$jspay_flag:1;
        }elseif ($pay_way == 'UPSMZF'){
            $jspay_flag = 0;
        } else{
            return false;
        }

        if ($jspay_flag == 2){
            $openid = '';
        }


        $params = array(
            'merchant_id'=>$param['merchant_no'],
            'service'=>'get_tdcode',
            'pay_way'=> $pay_way,
            'body'=>'order',
            'jspay_flag'=>$jspay_flag,
            'nonce_str'=>$this->nonce_str(),
            'sub_openid'=>$openid,
            'third_order_id'=>$param['ordersn'],
            'amount'=>$amount,
            'order_expiration' => '600',
            'notify_url'=>$notify_url,
            't0'=>0,
            'callback_url'=>($notify_url),
            'jump_url'=>$notify_url,
            'attach'=>$param['orderid'],
            'front_url'=>($notify_url),
        );

        if ($pay_way == 'WXZF'){
            $params['appid'] = $param['appid'];
        }

        //记录每笔订单的支付参数
        \think\Log::info(json_encode($params));

        $param_str = $this->sign($params,$param['verifycode']);

        \think\Log::info($param_str);

        //保存生成的验签
        Db('orderSign')->insert(array('sign'=>$param_str, 'ordersn'=>$param["ordersn"], 'status'=>1, 'createtime'=>time(),'custom'=>$params['attach'], 'frpcode'=>$pay_way,'merchant_no'=>$param['merchant_no'],'order_lists_id' => $param['orderid'], 'nonce_str' => $params['nonce_str']));


        //response
        $filecontent = $this->post($this->url, $param_str);
        $simpleXMLElement = simplexml_load_string($filecontent, 'SimpleXMLElement', LIBXML_NOCDATA);

        $result = json_decode(json_encode($simpleXMLElement), true);
        $return = ['code' => 100,'msg' => '','data'=> [] ];

        if (!isset($result['error_code']) && $result['resp_code'] == 0){

            if ($param['paytype'] == 'alipay'){
                $returnInfo = $result['td_code'];
            }else{
                $returnInfo = json_decode($result['jspay_info'], true);
            }

            $return['data'] = $returnInfo;
        }else{
            $return['code'] = $result['resp_code'] < 0?$result['resp_code']:$result['error_code'];
            $return['msg']  = $result['resp_code'] < 0?$result['resp_msg']:$result['error_msg'];
        }

        return $return;
    }

    public function queryOrder($args){
        $param = array('merchant_id'=>$this->merchant_id,
            'service'=>'query_status',
            'nonce_str'=>$this->nonce_str(),
            'third_order_id'=>$args['order'],
        );

        //request
        $param_str = $this->sign($param);

        //response
        $filecontent = $this->post($this->url, $param_str);
        return simplexml_load_string($filecontent);
    }

    /**
     * 被扫支付，刷卡支付
     */
    public function upTdCode($amount, $order_id, $tdcode){
        $param = array('merchant_id'=>$this->merchant_id,
            'service'=>'upload_authcode',
            'pay_way'=>'WXZF',
            'body'=>'支付',
            'auth_code'=>$tdcode,
            'nonce_str'=>$this->nonce_str(),
            'third_order_id'=>$order_id,
            'amount'=>$amount,
            'notify_url'=>$this->callback_url,
            't0'=>0,'callback_url'=>$this->callback_url);
        $param_str = $this->sign($param);
        echo($param_str.PHP_EOL);

        //response
        $filecontent = $this->post($this->url, $param_str);
        echo($filecontent).PHP_EOL;
        $re_obj = simplexml_load_string($filecontent);
        // var_dump($re_obj);
        return $re_obj;
    }


    //退款
    public function refund($amount, $order_id){
        $merchantid = pdo_fetchcolumn('select merchid from ' . tablename('ewei_shop_payinfo') . ' where ordersn=:ordersn and isdeleted=0 ', array(':ordersn' => $order_id));
        $param = array('merchant_id'=>$merchantid,
            'service'=>'unified_refund',
            'nonce_str'=>$this->nonce_str(),
            'third_order_id'=>$order_id,
            'refund_amount'=>$amount,
        );

        $param['merchant_refund_id'] = $param['third_order_id'].'T1';


        $param_str = $this->sign($param);

        //response
        $filecontent = $this->post($this->url, $param_str);
        $obj = simplexml_load_string($filecontent, 'SimpleXMLElement', LIBXML_NOCDATA);

        $data = json_decode(json_encode($obj), true);

        if ($data['result_code'] != 0){
            return error(-2, $data['error_msg']);
        }

        if ($data['resp_code'] == 0){
            return true;
        }else{
            return error(-2, $data['error_msg']);
        }

        return $re_obj;
    }

        //查询商户信息
    public function getMerchInfo($merchid){
        //ip
        $url = 'http://120.76.53.120:8082';
        $path = $url . '/merchantinfo/' . $merchid;

        $response = ihttp_get($path);
        if ($response['code'] == 200){
            $data = json_decode($response['content'], true);
            return $data['data'];
        }else{
            return false;
        }
    }

    //查询商户余额
    public function getBalance($merchid){
        //ip
        $url = 'http://120.76.53.120:8082';
        $path = $url . '/balance/blancemessage/' . $merchid;

        $response = ihttp_get($path);

        if ($response['code'] == 200){
            $data = json_decode($response['content'], true);
            return $data['data'];
        }else{
            return false;
        }
    }

    //提现
    public function withdraw($merchid,$money){
        $url = 'http://120.76.53.120:8082';
        $path = $url . '/merchantWithdraw';

        $param = array(
            'merchantId'      => $merchid,
            'refund_amount'   => $money
        );
        $response = ihttp_post($path,$param);

        if ($response['code'] == 200){
            $data = json_decode($response['content'], true);
            return $data['data'];
        }else{
            return false;
        }

    }

        //修改提现方式
    public function changewithdraw($merchid,$type){
        $url = 'http://120.76.53.120:8082';
        $path = $url . '/withdrawset';

        $param = array(
            'merchantId'      => $merchid,
            'withDrawType'   =>  $type
        );
        $response = ihttp_post($path,$param);

        if ($response['code'] == 200){
            $data = json_decode($response['content'], true);

            return $data['data'];
        }else{
            return false;
        }

    }

    public function cancel($merchid,$third_order_id){
        global $_W;

        $param = array(
            'service'=>'close_order',
            'merchant_id'=>$merchid,
            'third_order_id'=>$third_order_id,
            'nonce_str'=>$this->nonce_str(),
        );
        $param_str = $this->sign($param);
        //response
        $filecontent = $this->post($this->url, $param_str);
        $re_obj = simplexml_load_string($filecontent,'SimpleXMLElement' , LIBXML_NOCDATA );

        return (array)$re_obj;
//        var_dump($re_obj);exit();
//        $re_obj['jspay_info'] = json_decode($re_obj['jspay_info'], true);
//        $re_obj['signs'] = $this->signs($param);
//        $re_obj['nonce_str'] = $param['nonce_str'];
//        $re_obj['openid'] = $openid;
//        return $re_obj;
    }

    public function post($url, $data){
        $ch = curl_init();
        $header = array();
        $header[] = 'Content-Type:application/x-www-form-urlencoded';
//        echo $url.PHP_EOL;
        curl_setopt($ch, CURLOPT_URL, $this->url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HEADER, 0);//设定是否输出页面内容
        //curl_setopt($ch,CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1); // post,get 过去
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不验证证书
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,10);

        //curl_setopt($ch, CURLOPT_PROXY, '192.168.0.12'); //代理服务器地址
        //curl_setopt($ch, CURLOPT_PROXYPORT, 8888); //代理服务器端口
//        echo('post ' . $url . '?' . $data);
        $filecontent = curl_exec($ch);
//        echo($filecontent);
        return $filecontent;
    }

    /**
     * 参数签名
     */
    private function sign($param, $key){
        ksort($param);
        $mparam = $param;
        $queryParam_arr = array();
        foreach($param as $k=>$v){
            $queryParam_arr[] = $k."=".$v;
        }

        $queryParam = implode("&", $queryParam_arr);
        $sign = strtoupper(md5($queryParam.'&key='.$key));
        $mqueryParam_arr = array();
        foreach($mparam as $k=>$v){
            $mqueryParam_arr[$k] = $v;
        }
        $mqueryParam_arr['sign'] = $sign;
//        echo($sign);
        return  http_build_query($mqueryParam_arr);
    }

    private function signs($param){
        ksort($param);
        $mparam = $param;
        $queryParam_arr = array();
        foreach($param as $k=>$v){
            $queryParam_arr[] = $k."=".$v;
        }

        $queryParam = implode("&", $queryParam_arr);

        return   strtoupper(md5($queryParam.'&key='.$this->key));
    }

    /**
     *
     */
    private function nonce_str() {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $length = strlen($characters);
        $nonce_str = '';
        for ($i = 0; $i < 16; $i++) {
            $nonce_str .= $characters[rand(0, $length - 1)];
        }
        return $nonce_str;
    }
}

/**
 * 生成商户自己的订单号，乐刷会返回乐刷的订单号，不是这里生成的
 * 接口字段中的third_order_id
 */

